﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Security;
using Cofe.Web.Models;
using WebMatrix.WebData;
using Cofe.Web.Utils;
using Cofe.Core.Security;
using Cofe.Core;

namespace Cofe.Web
{
    //http://kevin-junghans.blogspot.hk/2013/01/seeding-customizing-aspnet-mvc.html
    public class InitSecurityDb : DropCreateDatabaseIfModelChanges<UsersContext>
    {
        protected override void Seed(UsersContext context)
        {
            WebSecurity.InitializeDatabaseConnection("DefaultConnection",
               "UserProfile", "UserId", "UserName", autoCreateTables: true);
            var roles = (SimpleRoleProvider)Roles.Provider;
            var membership = (SimpleMembershipProvider)Membership.Provider;
        }
    }

    public static class SecurityConfig
    {
        public static void RegisterDatabase()
        {
            Database.SetInitializer<UsersContext>(new InitSecurityDb());
            UsersContext context = new UsersContext();
            context.Database.Initialize(true);
            if (!WebSecurity.Initialized)
                WebSecurity.InitializeDatabaseConnection("DefaultConnection",
                    "UserProfile", "UserId", "UserName", autoCreateTables: true);

            RegisterRoles();
        }

        public static void RegisterAsAdmin(string userName)
        {
            var roles = (SimpleRoleProvider)Roles.Provider;
            if (!(roles.GetRolesForUser(userName).Contains(WebUserRole.Admin.GetRoleString())))
                roles.AddUsersToRoles(new string[] { userName }, new string[] { WebUserRole.Admin.GetRoleString() });
        }

        public static void GrandAdminAccessToAllVolume()
        {
            //Admin can access all volume
            CofeServices.SecurityManager.ServicePermissionPolicies.Add(VolumePermissionPolicy.ForAllVolume(
                new string[] { WebUserRole.Admin.GetRoleString() }, PermissionType.All));

        }

        public static void RegisterRoles()
        {
            var roles = (SimpleRoleProvider)Roles.Provider;
            var membership = (SimpleMembershipProvider)Membership.Provider;

            foreach (var wr in WebUserRoleUtils.PossibleRoles)
                if (!roles.RoleExists(wr.GetRoleString()))
                    roles.CreateRole(wr.GetRoleString());      

          

        }
    }
}